//
//  main.c
//  顺序表
//
//  Created by 解楚豪 on 2018/8/8.
//  Copyright © 2018年 解楚豪. All rights reserved.
//

#include <stdio.h>
#include <stdlib.h>

#define Size 4
typedef struct Table {
    int *head;
    int length;
    int size;
}table;
//初始化
table initTable(){
    table tb;
    
    tb.head = (int*)malloc(sizeof(int));
    if (!tb.head) {
        printf("初始化失败");
        exit(0);
    }
    
    tb.length = 0;
    tb.size = Size;
    return tb;
}
//查找元素
int selectTable(table t, int elem){
    for (int i=0; i<t.length; i++) {
        if (t.head[i] == elem) {
            return i+1;
        }
    }
    return -1;//如果查找失败
}
//更改元素
table amendTable(table t,int elem,int newElem){
    int add = selectTable(t, elem);
    t.head[add-1] = newElem;
    return t;
}
//添加
table addTable(table t, int add, int elem){
    if (add > t.length+1 || add < 1) {
        printf("插入顺序错误");
        return t;
    }
    
    if (t.length == t.size) {
        t.head = (int *)realloc(t.head, (t.size + 1)*sizeof(int));
        if (!t.head) {
            printf("分配内存失败");
            return t;
        }
        t.size += 1;
    }
    
    for (int i=t.length-1; i>=add-1; i--) {
        t.head[i+1] = t.head[i];
    }
    
    t.head[add] = elem;
    t.length++;
    
    return t;
}
//删除
table delTable(table t,int add){
    if (add > t.length || add < 1) {
        printf("删除下标错误");
        return t;
    }
    
    for (int i=add; i<t.length; i++) {
        t.head[i-1] = t.head[i];
    }
    t.length--;
    return t;
}
//读取
void display(table t){
    for (int i=0; i<t.length; i++) {
        printf("%d ",t.head[i]);
    }
    printf("\n");
}
int main(int argc, const char * argv[]) {
    table t = initTable();
    for (int i=0; i<Size; i++) {
        t.head[i] = i+1;
        t.length++;
    }
    
    printf("原顺序表:\n");
    display(t);
    
    printf("添加元素:\n");
    t = addTable(t, 2, 10);
    display(t);
    
    printf("删除元素:\n");
    t = delTable(t, 2);
    display(t);
    
    printf("修改元素:\n");
    t = amendTable(t, 3, 6);
    display(t);
    
    printf("查询元素3的下标:\n");
    int threeData = selectTable(t, 3);
    printf("%d \n",threeData);
    
    return 0;
}
